package com.xy.order.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VideoTools {


    //输出文件名称(一般为书名)
    private static String fileName = "g341";

    //空格，四格位置
    private static String space = "    ";

    //文件输出流
    private static FileWriter writer;


    //输出到文件
    public static void outputToFile(Document document) throws IOException {
        String title = getTitle(document);
        String content = getContent(document);
        String text = space + title + "\r\n\r\n" + content;
        System.out.printf("===>爬到第"+title+"章");
        writer.write(text);
        writer.flush();
        try {
            Thread.sleep(1600);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("===>爬取完成，准备下一章");
    }


    //获取输出流
    public static void getWriter() throws IOException {
        String path = "D:/" + fileName + ".txt";
        File file = new File(path);
        if (file.exists()) {
            System.out.println("目标书籍已存在!请修改文件名或删除原书籍 " + path);
            System.exit(0);
        }
        writer = new FileWriter(file);
    }

    public static String getVideoUrl(String htmlUrl) throws JSONException {
        // 正则表达式解析地址，取id
        Pattern p = Pattern.compile(".*id_(\\w+)\\.html");
        String u = htmlUrl;
        Matcher m = p.matcher(u);
        String id = "";
        if (m.find()) {
            id = m.group(1);
        }
        System.out.println(id);

        id="XNjIyMjY3NjcyOA";
        String s = getContent("http://v.youku.com/player/getPlayList/VideoIDS/"
                + id);
        System.out.print(s);
        JSONObject jsobj = JSONObject.parseObject(s);

        JSONArray jsonarr = jsobj.getJSONArray("data");
        System.out.println(jsobj);
        JSONObject obj1 = jsonarr.getJSONObject(0);
        String title = obj1.getString("title");
        double seed = obj1.getDouble("seed");
        JSONObject obj2 = obj1.getJSONObject("streamfileids");
        String mp4id = null;
        String flvid = null;
        String format = null;
        try {
            mp4id = obj2.getString("mp4");
            format = "mp4";
        } catch (JSONException e) {
            System.out.println("没有MP4格式");
            try {
                flvid = obj2.getString("flv");
                format = "flv";
            } catch (JSONException e1) {
                System.out.println("没有FLV格式");
                return "";
            }
        }
        String realfileid = null;
        if (format.equals("mp4")) {
            realfileid = getFileID(mp4id, seed);
        } else {
            realfileid = getFileID(flvid, seed);
        }

        String idLeft = realfileid.substring(0, 8);
        String idRight = realfileid.substring(10);

        String sid = genSid();
        JSONObject obj3 = obj1.getJSONObject("segs");
        JSONArray mp4arr = obj3.getJSONArray(format);
        String VideoUrl = "";
        for (int i = 0; i < mp4arr.size(); i++) {
            JSONObject o = mp4arr.getJSONObject(i);
            String k = o.getString("k");
            String url = "http://f.youku.com/player/getFlvPath/sid/" + sid
                    + "_" + String.format("%1$02X", i) + "/st/" + format
                    + "/fileid/" + idLeft + String.format("%1$02X", i)
                    + idRight + "?K=" + k;
            System.out.println(url);
            VideoUrl += url + "#";
        }
        return VideoUrl;
    }

    private static String getFileID(String fileid, double seed) {
        String mixed = getFileIDMixString(seed);
        String[] ids = fileid.split("\\*");
        StringBuilder realId = new StringBuilder();
        int idx;
        for (int i = 0; i < ids.length; i++) {
            idx = Integer.parseInt(ids[i]);
            realId.append(mixed.charAt(idx));
        }
        return realId.toString();
    }

    public static String genSid() {
        int i1 = (int) (1000 + Math.floor(Math.random() * 999));
        int i2 = (int) (1000 + Math.floor(Math.random() * 9000));
        return System.currentTimeMillis() + "" + i1 + "" + i2;
    }

    private static String getFileIDMixString(double seed) {
        StringBuilder mixed = new StringBuilder();
        StringBuilder source = new StringBuilder(
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\\:._-1234567890");
        int index, len = source.length();
        for (int i = 0; i < len; ++i) {
            seed = (seed * 211 + 30031) % 65536;
            index = (int) Math.floor(seed / 65536 * source.length());
            mixed.append(source.charAt(index));
            source.deleteCharAt(index);
        }
        return mixed.toString();
    }

    public static String getContent(String strUrl) {
        try {

            URL url = new URL(strUrl);
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    url.openStream()));
            String s = "";
            StringBuffer sb = new StringBuffer("");
            while ((s = br.readLine()) != null) {
                sb.append(s);
            }
            br.close();
            return sb.toString();
        } catch (Exception e) {
            return "error open url:" + strUrl;
        }
    }

    //获取当前章节标题
    private static String getTitle(Document document) {
        Element element = document.select(".bookname").first(); // 选择第一个具有类名 "bookname" 的元素
        Element h1Element = element.select("h1").first(); // 在该元素中选择第一个 h1 标签
        String h1Value = h1Element.text(); // 获取 h1 标签的文本内容
        if (!StringUtil.isBlank(h1Value)) {
            System.out.println(h1Value);
            return h1Value;
        }
        return h1Value;
    }

    //获取章节具体内容
    public static String getContent(Document document) {
        String content = document
                .getElementById("content")
                .getElementsByTag("p")
                .html();
        return content;
    }





    //获取下一章节id
    public static String getNextId(Document document) {
        String nextId = null;
        Element element = document.select("a[data-nextcid]").first(); // 选择具有data-nextcid属性的第一个<a>标签
        if (element != null) {
            String dataNextcid = element.attr("data-nextcid");
            nextId = dataNextcid;
        } else {
            System.out.println("没有找到具有data-nextcid属性的<a>标签");
        }
        return nextId;
    }

    //获取下一章节id
    public static String getBiquNextId(Document document) {
        String nextId = null;
        Elements links = document.select("a:contains(下一章)"); // 选择文本为“下一章”的<a>标签
        String href = links.attr("href"); // 获取<a>标签的href属性值（绝对URL）
        return href;
    }

    //获取目录
    public static String getmuluId(Document document) {
        String nextId = null;
        Elements links = document.select("a:contains(章节目录)"); // 选择文本为“下一章”的<a>标签
        String href = links.attr("href"); // 获取<a>标签的href属性值（绝对URL）
        return href;
    }


    public Document getDocuNext(String url) {
        Document document = getHtmlJsoup(url);
        return document;
    }


    public void getNovelSrtr(String urlFirst) {
//        String urlBefore = "https://read.zongheng.com/chapter/1274613/";
        String urlBefore = "http://www.biquge5200.cc/";
        Document document = getDocuNext(urlBefore+urlFirst);
        try {
            outputToFile(document);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String nextId = getBiquNextId(getDocuNext(urlBefore+urlFirst));
        if(!nextId.equals(getmuluId(getDocuNext(urlBefore+urlFirst)))) {
                urlFirst = nextId;
                getNovelSrtr(urlFirst);
        }
    }

    static  Document getHtmlJsoup(String url) {
        String s = "";
        Connection conn = Jsoup.connect(url)
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
                .header("Accept-Encoding", "gzip, deflate")
                .header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                .header("Cache-Control", "max-age=0")
                .header("Connection", "keep-alive")
                .header("Host", url)
                .userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:49.0) Gecko/20100101 Firefox/49.0").ignoreHttpErrors(true).followRedirects(true).timeout(100000).ignoreContentType(true);
        try {
           return conn.execute().parse();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    static String gethtml(String ul) {
        String url = ul;
        InputStream is = null;
        InputStreamReader isr = null;
        try {
            URL u = new URL(url);
            HttpURLConnection uc = (HttpURLConnection) u.openConnection();
            //设置header
            uc.setRequestMethod("GET");
            uc.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3895.5 Safari/537.36");
            uc.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
//			uc.setRequestProperty("Accept-Encoding", "gzip, deflate");
            uc.setRequestProperty("Accept",
                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
            uc.setRequestProperty("Connection", "keep-alive");
            uc.connect();
            is = uc.getInputStream();
            isr = new InputStreamReader(is);
            StringBuffer sb = new StringBuffer("");
            char[] buff = new char[1024];
            int len = -1;
            while ((len = isr.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
            String s = new String(sb.toString().getBytes(), "UTF-8");
            return s;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                isr.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return "";
    }



    public static void main(String[] args) {
        VideoTools videoTools = new VideoTools();
        try {
            getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        videoTools.getNovelSrtr("0_757/567461.html");
    }
}